package main

import (
	"dash/warningnotices"
	"database/sql"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"time"
	kitlog "github.com/go-kit/kit/log"
	"gopkg.in/yaml.v2"
	_ "github.com/go-sql-driver/mysql"
)

var cfg struct {
	Username   string `yaml:"username"`
	Password   string `yaml:"password"`
	Host       string `yaml:"host"`
	MysqlPort  string `yaml:"mysqlPort"`
	Database   string `yaml:"database"`
	Charset    string `yaml:"charset"`
	ServerPort string `yaml:"serverPort"`
}

func init() {
	b, err := ioutil.ReadFile("config.yaml")
	if err != nil {
		panic(err)
	}
	err = yaml.Unmarshal(b, &cfg)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n", &cfg)
}

func main() {
	var logger kitlog.Logger
	{
		logger = kitlog.NewLogfmtLogger(os.Stdout)
		logger = kitlog.With(logger, "time", kitlog.DefaultTimestamp)
		logger = kitlog.With(logger, "caller", kitlog.DefaultCaller)
		// logger = logger
	}

	var mysqlDb *sql.DB
	var mysqlDbErr error

	dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", cfg.Username, cfg.Password, cfg.Host, cfg.MysqlPort, cfg.Database, cfg.Charset)
	// 打开连接失败
	mysqlDb, mysqlDbErr = sql.Open("mysql", dbDSN)
	defer mysqlDb.Close();
	if mysqlDbErr != nil {
		logger.Log("mysqlDSN", dbDSN)
		panic("数据源配置不正确:" + mysqlDbErr.Error())
	}

	// 最大连接数
	mysqlDb.SetMaxOpenConns(100)
	// 闲置连接数
	mysqlDb.SetMaxIdleConns(20)
	// 最大连接周期
	mysqlDb.SetConnMaxLifetime(100 * time.Second)
	if mysqlDbErr = mysqlDb.Ping(); nil != mysqlDbErr {
		panic("数据库链接失败: " + mysqlDbErr.Error())
	}

	var repository warningnotices.Repository = warningnotices.NewRepository(mysqlDb, logger)
	var collectorService warningnotices.WarningNoticeService = warningnotices.NewWarningNoticeService(repository, logger)
	handler := warningnotices.MakeWarningNoticeHandler(collectorService)
	logger.Log("start at port", cfg.ServerPort)
	http.ListenAndServe(cfg.ServerPort, handler)
}
